"""
游戏主逻辑模块，协调所有游戏组件。
"""
import sys
from typing import Dict, Optional, Tuple, List
import random

import pygame

from tetris.constants import (
    SCREEN_WIDTH, SCREEN_HEIGHT, FPS, P1_KEYS, P2_KEYS,
    GAME_STATE_MENU, GAME_STATE_PLAYING, GAME_STATE_PAUSED, GAME_STATE_GAME_OVER,
    BOARD_WIDTH, BOARD_HEIGHT, BLOCK_SIZE, BLACK
)
from tetris.player import Player
from tetris.ui import UI
from tetris.clean_board import CleanBoard
from tetris.tetromino import Tetromino


class Game:
    """游戏主类，管理游戏状态和逻辑"""
    
    def __init__(self):
        """初始化游戏 - 完全重写"""
        # 初始化pygame
        pygame.init()
        pygame.display.init()  # 确保显示子系统初始化
        pygame.display.quit()  # 完全关闭然后重新打开显示
        pygame.display.init()
        
        # 创建全新窗口
        self.screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
        pygame.display.set_caption("双人俄罗斯方块")
        
        # 强制多次清屏确保干净
        for _ in range(3):
            self.screen.fill(BLACK)
            pygame.display.flip()
            pygame.time.delay(50)
        
        # 创建其他组件
        self.clock = pygame.time.Clock()
        self.ui = UI(self.screen)
        
        # 游戏状态
        self.game_state = GAME_STATE_MENU
        self.players = []
        self.frame_count = 0
        
        # 创建玩家但不创建方块
        self.players = [
            Player(1, P1_KEYS, self.ui.p1_x, create_tetromino=False),
            Player(2, P2_KEYS, self.ui.p2_x, create_tetromino=False)
        ]
        
        # 确保游戏板是空的
        for player in self.players:
            player.board.grid = [[None for _ in range(BOARD_WIDTH)] for _ in range(BOARD_HEIGHT)]
        
        print("游戏初始化完成，按空格键开始！")
    
    def _init_players(self) -> None:
        """初始化玩家"""
        # 重置随机性
        Player._shared_random_initialized = False
        
        # 确保两个玩家同时创建
        self.players = [
            Player(1, P1_KEYS, self.ui.p1_x),
            Player(2, P2_KEYS, self.ui.p2_x)
        ]
        
        # 确认玩家初始化一致
        print(f"玩家1初始方块: {self.players[0].current_tetromino.shape_type}")
        print(f"玩家2初始方块: {self.players[1].current_tetromino.shape_type}")
    
    def run(self) -> None:
        """运行游戏主循环"""
        # 添加游戏开始标志和时间控制
        game_just_started = True
        last_time = pygame.time.get_ticks() / 1000.0
        
        while True:
            # 处理事件
            self._handle_events()
            
            # 计算精确的时间增量
            current_time = pygame.time.get_ticks() / 1000.0
            dt = current_time - last_time
            last_time = current_time
            
            # 限制dt值范围，防止游戏暂停后的时间跳跃
            if dt > 0.1:  # 如果帧率低于10fps
                dt = 0.1
            elif dt < 0.001:  # 防止除以零错误
                dt = 0.001
            
            # 游戏刚开始时，跳过第一帧更新
            if game_just_started and self.game_state == GAME_STATE_PLAYING:
                game_just_started = False
                dt = 0
                print("游戏开始！初始dt=0")
            
            # 每60帧输出一次帧率信息
            self.frame_count += 1
            if self.frame_count >= 60:
                self.frame_count = 0
                print(f"当前FPS: {1.0/dt:.1f}")
            
            # 更新游戏状态
            self._update(dt)
            
            # 渲染游戏
            self._render()
            
            # 限制帧率
            self.clock.tick(FPS)
    
    def _handle_events(self) -> None:
        """处理所有游戏事件"""
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                self._quit_game()
            
            elif event.type == pygame.KEYDOWN:
                self._handle_keydown(event.key)
    
    def _handle_keydown(self, key: int) -> None:
        """处理按键事件"""
        if key == pygame.K_ESCAPE:
            self._quit_game()
            
        elif key == pygame.K_p:
            # 切换暂停状态
            if self.game_state == GAME_STATE_PLAYING:
                self.game_state = GAME_STATE_PAUSED
            elif self.game_state == GAME_STATE_PAUSED:
                self.game_state = GAME_STATE_PLAYING
            
        elif key == pygame.K_r:
            # 重新开始游戏
            if self.game_state == GAME_STATE_GAME_OVER:
                self._reset_game()
            
        elif key == pygame.K_SPACE:
            # 从菜单开始游戏
            if self.game_state == GAME_STATE_MENU:
                self._reset_game()
    
    def _update(self, dt: float) -> None:
        """
        更新游戏状态
        
        Args:
            dt: 时间增量(秒)
        """
        if self.game_state != GAME_STATE_PLAYING:
            return
        
        # 获取按键状态
        keys_pressed = pygame.key.get_pressed()
        
        # 更新玩家状态
        for player in self.players:
            player.update(dt, keys_pressed)
            
        # 检查游戏结束，但在游戏开始的2秒内不检查
        game_time = max(player.game_time for player in self.players)
        if game_time > 2.0 and any(player.game_over for player in self.players):
            self.game_state = GAME_STATE_GAME_OVER
            print(f"游戏结束，经过时间: {game_time:.1f}秒")
            for player in self.players:
                if player.game_over:
                    print(f"玩家{player.player_id}游戏结束")
    
    def _render(self) -> None:
        """渲染游戏"""
        # 总是先清空整个屏幕
        self.screen.fill(BLACK)
        
        # 只在游戏开始的前1秒内执行清除，确保初始方块问题得到解决
        if self.game_state == GAME_STATE_PLAYING:
            game_time = max(player.game_time for player in self.players)
            if game_time < 1.0:  # 只在游戏开始的第一秒执行清除
                for player in self.players:
                    for y in range(BOARD_HEIGHT):
                        for x in range(BOARD_WIDTH):
                            cell = player.board.grid[y][x]
                            # 只针对底部区域的粉色方块进行清除
                            if cell == (255, 0, 255) and y > BOARD_HEIGHT // 2:
                                print(f"游戏开始阶段：发现并删除粉色方块在 ({x}, {y})")
                                player.board.grid[y][x] = None
        
        if self.game_state == GAME_STATE_MENU:
            self.ui.draw_title_screen()
            # 菜单状态不渲染任何方块
            
        elif self.game_state == GAME_STATE_PLAYING or self.game_state == GAME_STATE_PAUSED:
            # 绘制游戏板背景
            self.ui.draw_board_background(self.ui.p1_x, self.ui.p1_y)
            self.ui.draw_board_background(self.ui.p2_x, self.ui.p2_y)
            
            # 绘制玩家游戏板
            self.ui.draw_board(self.players[0].board.grid, self.ui.p1_x, self.ui.p1_y)
            self.ui.draw_board(self.players[1].board.grid, self.ui.p2_x, self.ui.p2_y)
            
            # 然后绘制当前方块
            if self.players[0].current_tetromino:
                self.ui.draw_tetromino(self.players[0].current_tetromino, self.ui.p1_x, self.ui.p1_y)
            
            if self.players[1].current_tetromino:
                self.ui.draw_tetromino(self.players[1].current_tetromino, self.ui.p2_x, self.ui.p2_y)
            
            # 其他UI元素...
            self.ui.draw_next_tetromino(self.players[0].next_tetromino, self.ui.p1_x - 150, self.ui.p1_y)
            self.ui.draw_score(self.players[0], self.ui.p1_x - 150, self.ui.p1_y + 200)
            self.ui.draw_controls(self.players[0], self.ui.p1_x - 150, self.ui.p1_y + 330)
            
            self.ui.draw_next_tetromino(self.players[1].next_tetromino, self.ui.p2_x + BOARD_WIDTH * 25 + 20, self.ui.p2_y)
            self.ui.draw_score(self.players[1], self.ui.p2_x + BOARD_WIDTH * 25 + 20, self.ui.p2_y + 200)
            self.ui.draw_controls(self.players[1], self.ui.p2_x + BOARD_WIDTH * 25 + 20, self.ui.p2_y + 330)
            
            # 如果游戏暂停，绘制暂停画面
            if self.game_state == GAME_STATE_PAUSED:
                self.ui.draw_pause_screen()
                
        elif self.game_state == GAME_STATE_GAME_OVER:
            # 绘制游戏板
            self.ui.draw_board(self.players[0].board.grid, self.ui.p1_x, self.ui.p1_y)
            self.ui.draw_board(self.players[1].board.grid, self.ui.p2_x, self.ui.p2_y)
            
            # 确定哪个玩家输了
            game_over_player_id = next((player.player_id for player in self.players if player.game_over), None)
            if game_over_player_id:
                self.ui.draw_game_over(game_over_player_id)
        
        # 更新屏幕
        pygame.display.flip()
    
    def _quit_game(self) -> None:
        """退出游戏"""
        pygame.quit()
        sys.exit()
    
    def _reset_game(self) -> None:
        """完全重置游戏状态 - 终极彻底版本"""
        # 清除所有状态，重新初始化
        Player._shared_random_initialized = False
        random.seed()
        
        # 强制多次清屏
        for _ in range(5):  # 增加到5次
            self.screen.fill(BLACK)
            pygame.display.flip()
            pygame.time.delay(100)  # 增加延迟
        
        # 完全销毁并重建玩家
        self.players = []
        pygame.time.delay(200)  # 等待更长时间确保资源释放
        
        # 创建全新的玩家
        self.players = [
            Player(1, P1_KEYS, self.ui.p1_x, create_tetromino=True),
            Player(2, P2_KEYS, self.ui.p2_x, create_tetromino=True)
        ]
        
        # 执行紧急清理
        self._emergency_cleanup()
        
        # 游戏状态也完全重置
        self.game_state = GAME_STATE_PLAYING
        self.frame_count = 0
        self.clock.tick()
        
        print("游戏已完全重置 - 终极彻底清空版本")
        print("玩家1初始方块:", self.players[0].current_tetromino.shape_type)
        print("玩家2初始方块:", self.players[1].current_tetromino.shape_type)
    
    def _force_clear_all_boards(self) -> None:
        """完全终止强制清除，我们将使用更彻底的解决方案"""
        # 这个函数现在什么都不做，因为我们将采用更彻底的方法
        pass
    
    def _force_clean_render(self) -> None:
        """临时强制使用干净的游戏板进行一次渲染"""
        # 保存原始游戏板
        original_boards = [player.board.grid.copy() for player in self.players]
        
        # 替换为空白游戏板
        clean_board = [[None for _ in range(BOARD_WIDTH)] for _ in range(BOARD_HEIGHT)]
        for player in self.players:
            player.board.grid = clean_board.copy()
        
        # 强制渲染
        self.screen.fill(BLACK)
        self.ui.draw_board(self.players[0].board.grid, self.ui.p1_x, self.ui.p1_y)
        self.ui.draw_board(self.players[1].board.grid, self.ui.p2_x, self.ui.p2_y)
        pygame.display.flip()
        
        # 恢复原始游戏板
        for i, player in enumerate(self.players):
            player.board.grid = original_boards[i]
        
        print("强制清洁渲染完成")
    
    def _emergency_cleanup(self) -> None:
        """紧急清理 - 强制移除所有游戏板上的方块（最终解决方案）"""
        
        # 完全重建所有游戏板
        for player in self.players:
            # 创建全新的网格
            player.board.grid = [[None for _ in range(BOARD_WIDTH)] for _ in range(BOARD_HEIGHT)]
            
            # 仅保留当前活动方块
            if player.current_tetromino:
                # 先备份当前方块
                current_x = player.current_tetromino.x
                current_y = player.current_tetromino.y
                current_type = player.current_tetromino.shape_type
                current_rotation = player.current_tetromino.rotation
                
                # 创建新的方块（避免任何引用问题）
                player.current_tetromino = Tetromino(current_x, current_y, current_type)
                player.current_tetromino.rotation = current_rotation
        
        # 强制重新渲染
        self.screen.fill(BLACK)
        pygame.display.flip() 